package com.fayou.cloud.seatastorageservice2002.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fayou.cloud.seatastorageservice2002.entity.StorageTbl;
import com.fayou.cloud.seatastorageservice2002.dao.StorageTblDao;
import com.fayou.cloud.seatastorageservice2002.service.StorageTblService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (StorageTbl)表服务实现类
 *
 * @author makejava
 * @since 2020-06-03 20:00:03
 */
@Service("storageTblService")
public class StorageTblServiceImpl implements StorageTblService {
    @Resource
    private StorageTblDao storageTblDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public StorageTbl queryById(Integer id) {
        return this.storageTblDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<StorageTbl> queryAllByLimit(int offset, int limit) {
        return this.storageTblDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param storageTbl 实例对象
     * @return 实例对象
     */
    @Override
    public StorageTbl insert(StorageTbl storageTbl) {
        this.storageTblDao.insert(storageTbl);
        return storageTbl;
    }

    /**
     * 修改数据
     *
     * @param storageTbl 实例对象
     * @return 实例对象
     */
    @Override
    public StorageTbl update(StorageTbl storageTbl) {
        this.storageTblDao.update(storageTbl);
        return this.queryById(storageTbl.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public Boolean deleteById(Integer id) {
        return this.storageTblDao.deleteById(id) > 0;
    }



    /**
     * 减库存
     *
     * @param commodityCode
     * @param count
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deduct(String commodityCode, Integer count) {
        if (commodityCode.equals("product-2")) {
            throw new RuntimeException("异常:模拟业务异常:Storage branch exception");
        }

        QueryWrapper<StorageTbl> wrapper = new QueryWrapper<>();
        wrapper.setEntity(new StorageTbl().setCommodityCode(commodityCode));
        StorageTbl storage = storageTblDao.selectOne(wrapper);
        storage.setCount(storage.getCount() - count);

        storageTblDao.updateById(storage);
    }
}